# -*- coding: utf-8 -*-
import hashlib
import xml
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.utils.encoding import smart_str
from wechatpa import wechatpa




def wechat(request):
    if request.method == 'GET':
        try:
            signature = request.GET.get("signature")
            timestamp = request.GET.get("timestamp")
            nonce = request.GET.get("nonce")
            echostr = request.GET.get("echostr")
            token = wechatpa.WECHAT_FUWU["token"]

            if signature and timestamp and nonce and echostr:
                sortlist = [token, timestamp, nonce]
                sortlist.sort()
                sha = hashlib.sha1()
                sha.update("".join(sortlist))
                sha_str = sha.hexdigest()
                if sha_str == signature:
                    return HttpResponse(echostr)
                else:
                    return HttpResponseBadRequest('Verify Failed')
            else:
                return HttpResponseBadRequest('Verify Failed')
        except Exception:
            return HttpResponse('')
        # 如果是POST方法，提取xml数据
    else:
        xml_str = smart_str(request.body)
        # 解析本次请求的 XML 数据
        try:
            request_xml = xml.sax.parse(xml_str)
            request_dict = request_xml["xml"]
            msgtype = request_dict["MsgType"]
            touser = request_dict["FromUserName"]

            # 如果是文本、语音消息
            if msgtype in ["text", "voice"]:
                if msgtype == "voice":
                    content = request_dict["Recognition"].replace('！', '').replace('。', '')
                else:
                    content = request_dict["Content"]
                # res_text = response_search(touser, content, mtype=msgtype)
                res_text="hello"
                return HttpResponse(res_text, content_type='text/xml')

            # 如果是事件消息
            elif msgtype == "event":
                res_text = ''
                # 关注事件
                if request_dict["Event"] == "subscribe":
                    res_content = """人大学子,欢迎你关注高校IT（<a href="http://www.baidu.com">baidu.com</a>）。"""
                    res_text = wechatpa.response_text(touser, res_content)
                # 点击查企业
                elif request_dict["Event"] == "CLICK" and request_dict["EventKey"] == "entsearch":
                    res_content = """在微信中切换菜单为输入框，输入关键词，点击您想关注的企业，我们将为您推送该企业相关的风险监控信息（支持语音输入哦）。"""
                    res_text = wechatpa.response_text(touser, res_content)
                return HttpResponse(res_text, content_type='text/xml')

            else:
                return HttpResponse('')
        except Exception:
            return HttpResponse('')








